package cn.com.huzo.webapp.controller.trade;

import huzofw.common.web.controller.BaseFormController;
import cn.com.huzo.model.entities.trade.ProductionInstructionHeaderEntity;
import cn.com.huzo.model.entities.trade.ProductionInstructionLinesColourOrderEntity;
import cn.com.huzo.model.entities.trade.ProductionInstructionLinesDestinationEntity;
import cn.com.huzo.model.entities.trade.ProductionInstructionLinesEntity;
import cn.com.huzo.model.entities.trade.ProductionInstructionLinesSuitStyleNoEntity;
import cn.com.huzo.model.entities.trade.ProductionInstructionLinesSuitSizeEntity;
import cn.com.huzo.model.entities.trade.ProductionInstructionLinesPictureEntity;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import cn.com.huzo.service.trade.ProductionInstructionHeaderManager;
import cn.com.huzo.service.trade.ProductionInstructionLinesDestinationManager;
import cn.com.huzo.service.trade.ProductionInstructionLinesManager;
import cn.com.huzo.service.trade.ProductionInstructionLinesPictureManager;
import cn.com.huzo.service.trade.ProductionInstructionLinesScheduleManager;
import cn.com.huzo.service.trade.ProductionInstructionLinesSuitSizeManager;
import cn.com.huzo.service.trade.ProductionInstructionLinesSuitStyleNoManager;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections4.MapUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

/**
 * 生产指示书控制器
 *
 * @author 吴旭
 */
@Controller
@RequestMapping(value = "/trade/production_instruction")
public class ProductionInstructionController extends BaseFormController {

    // <editor-fold defaultstate="collapsed" desc="属性">
    @Resource(name = "ProductionInstructionHeaderManager")
    private ProductionInstructionHeaderManager _manager;

    @Resource(name = "ProductionInstructionLinesSuitStyleNoManager")
    private ProductionInstructionLinesSuitStyleNoManager _manager_lines_suite_styleno;

    @Resource(name = "ProductionInstructionLinesManager")
    private ProductionInstructionLinesManager _manager_lines;

    @Resource(name = "ProductionInstructionLinesScheduleManager")
    private ProductionInstructionLinesScheduleManager _manager_lines_schdule;

    @Resource(name = "ProductionInstructionLinesDestinationManager")
    private ProductionInstructionLinesDestinationManager _manager_lines_destination;

    @Resource(name = "ProductionInstructionLinesSuitSizeManager")
    private ProductionInstructionLinesSuitSizeManager _manager_lines_suite_size;

    @Resource(name = "ProductionInstructionLinesPictureManager")
    private ProductionInstructionLinesPictureManager _manager_lines_pic;

    @Resource(name = "freemarkerConfig")
    private FreeMarkerConfigurer freemarkerConfig;
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="画面处理部分">
    /**
     * 跳转到生产指示书一览画面
     * <p>
     * @param request
     * @return
     */
    @RequestMapping("/list.html")
    public ModelAndView redirectListWnd(HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("trade.production_instruction.list.def");
        return view;
    }

    /**
     * 生产指示书编辑画面
     * <p>
     * @param request 上下文请求
     * @param action 操作标志 1;增加 2：编辑
     * @param moId 生产指示书标识
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/{action}/{moId}/edit.html",
            method = {RequestMethod.GET})
    public ModelAndView redirectEditWnd(HttpServletRequest request, @PathVariable(value = "action") int action,
            @PathVariable(value = "moId") Long moId) throws Exception {
        ModelAndView view = new ModelAndView();
        view.addObject("action", action);
        view.addObject("moId", moId.toString());
        String strImageUrl = "http://" + request.getServerName() // 服务器地址  
                + ":"
                + request.getServerPort() // 端口号  
                + "/erpimg";
        view.addObject("strImageUrl", strImageUrl);    // 设置图片显示路径
        view.setViewName("trade.production_instruction.edit.def");
        return view;
    }

    /**
     * 生产指示书-明细增加画面
     * <p>
     * @return
     */
    @RequestMapping("/lines/cross_input/wizard.html")
    public ModelAndView redirectNewLinesWizardWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.trade.production_instruction_edit_lines_cross_input.wizard.def");
        return view;
    }

    /**
     * 设置唛头号画面
     * <p>
     * @return
     */
    @RequestMapping("/lines/shippingmark/edit.html")
    public ModelAndView redirectMoLinesEditShippingMarkNoPopupWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.trade.production_instruction_edit_lines_shippingmark.edit.def");
        return view;
    }

    /**
     * 设置交付日期（增加、删除、修改）
     *
     * @return
     */
    @RequestMapping("/lines/schedule/edit.html")
    public ModelAndView redirectMoLinesEditSchedulePopupWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.trade.production_instruction_edit_lines_schedule.edit.def");
        return view;
    }

    /**
     * 编辑发货目的地
     *
     * @return
     */
    @RequestMapping("/lines/destination/edit.html")
    public ModelAndView redirectMoLinesEditDestinationPopupWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.trade.production_instruction_edit_lines_destination.edit.def");
        return view;
    }

    /**
     * 编辑套装款号
     *
     * @return
     */
    @RequestMapping("/lines/suit_styleno/edit.html")
    public ModelAndView redirectMoLinesEditSuitStyleNoPopupWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.trade.production_instruction_edit_lines_suitstyleno.edit.def");
        return view;
    }

    /**
     * 编辑套装尺码
     *
     * @param linesId 所属明细ID
     * @return
     */
    @RequestMapping("/lines/suit_size/{linesId}/edit.html")
    public ModelAndView redirectMoLinesEditSuitSizePopupWnd(@PathVariable(value = "linesId") String linesId) {
        ModelAndView view = new ModelAndView();
        view.addObject("linesId", linesId);
        view.setViewName("popup.trade.production_instruction_edit_lines_suitsize.edit.def");
        return view;
    }

    /**
     * 每色新增尺码
     *
     * @param headerId 生产指示书ID
     * @return
     * @throws java.lang.Exception
     */
    @RequestMapping("/lines/suit_size/{hederId}/add.html")
    public ModelAndView redirectMoLinesAddSizePerColourPopupWnd(
            @PathVariable(value = "hederId") Long headerId) throws Exception {
        ModelAndView view = new ModelAndView();
        view.addObject("ColourList", _manager_lines.fetchProductColourFromMoByHeaderId(headerId));
        view.setViewName("popup.trade.production_instruction_edit_lines_suitsize.add.def");
        return view;
    }

    /**
     * 颜色显示顺序
     *
     * @return
     */
    @RequestMapping("/lines/colour_order/edit.html")
    public ModelAndView redirectMoLinesEditColourOrderPopupWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.trade.production_instruction_edit_lines_colour_order.edit.def");
        return view;
    }

    /**
     * 弹出生产指示书选择画面
     *
     * @return
     */
    @RequestMapping("/choice.html")
    public ModelAndView redirectMoChoiceWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.trade.production_instruction.choice.def");
        return view;
    }

    /**
     * 弹出生产指示书颜色选择画面
     *
     * @return
     */
    @RequestMapping("/product_colour/choice.html")
    public ModelAndView redirectMoProductColourChoiceWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.trade.production_instruction_product_colour.choice.def");
        return view;
    }

    /**
     * 弹出生产指示书尺码选择画面
     *
     * @return
     */
    @RequestMapping("/product_size/choice.html")
    public ModelAndView redirectMoProductSizeChoiceWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("popup.trade.production_instruction_product_size.choice.def");
        return view;
    }

    /**
     * 生产指示书-打印预览画面
     * <p>
     * @return
     */
    @RequestMapping("/print.html")
    public ModelAndView redirectPrintPreviewWnd() {
        ModelAndView view = new ModelAndView();
        view.setViewName("print.trade.production_instruction.print.def");
        return view;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="主表-数据处理部分">
    /**
     * 根据标识取得生产指示书数据。
     *
     * @param criterion 生产指示书标识、当前用户、流程标识
     * @return 生产指示书数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/fetchByKey.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchByHeaderId(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager.fetchByHeaderId(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "CurrentUserId"),
                MapUtils.getLong(criterion, "WorkFlowId"));
    }

    /**
     * 根据款号取得生产指示书数据。
     *
     * @param styleNo 款号
     * @return 生产指示书数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/fetchByStyleNo.html",
            method = RequestMethod.POST)
    public @ResponseBody
    ProductionInstructionHeaderEntity fetchByStyleNo(@RequestBody final String styleNo) throws Exception {
        return _manager.fetchByStyleNo(styleNo);
    }

    /**
     * 删除生产指示书计划数据。
     *
     * @param criterion 生产指示书标识
     * @return 返回删除后的数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/header/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> delete(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager.delete(criterion);
    }

    /**
     * 根据条件取得生产指示书分页数据。
     * <p>
     * @param criterion 检索条件
     * @return 生产指示书分页数据
     * @throws Exception
     */
    @RequestMapping(value = "/fetchForPage.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchForPage(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager.fetchForPage(criterion);
    }

    /**
     * 保存生产指示书数据。
     * <p>
     * @param instance 要保存的生产指示书对象。
     * @return 新增记录主键.
     * @throws Exception
     */
    @RequestMapping(value = "/header/save.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Long save(@RequestBody final ProductionInstructionHeaderEntity instance) throws Exception {
        Long rowsAffected;

        if (instance.getHeaderId() > 0) { //编辑
            rowsAffected = (long) _manager.update(instance);
        } else {//新增
            rowsAffected = _manager.insert(instance);
        }

        return rowsAffected;
    }

    /**
     * 根据生产指示书标识取得款号明细
     *
     * @param headerId 生产指示书标识
     * @return 款明细
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/header/fetchStyleNoByHeaderKey.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<ProductionInstructionLinesSuitStyleNoEntity> fetchSuitStyleNoByHeaderId(
            @RequestBody final Long headerId) throws Exception {
        return _manager.fetchSuitStyleNoByHeaderId(headerId);
    }

    /**
     * 根据该生产指示书的款号得到对应的产品尺码（全部尺码，有可能不同色有不同的尺码，这里不做区分）。
     *
     * @param criterion 生产指示书标识、款号
     * @return 对应的尺码。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/fetchProductSizeByMoStyleNo.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<Map<String, Object>> fetchProductSizeByMoHeaderIdAndStyleNo(
            @RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager.fetchProductSizeByMoHeaderKeyAndStyleNo(
                MapUtils.getLong(criterion, "HeaderKey"),
                MapUtils.getString(criterion, "StyleNo"));
    }

    /**
     * 设置完成标记。
     *
     * @param criterion 条件
     * @return 影响行数
     * @throws Exception
     */
    @RequestMapping(value = "/setOverFlag.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Integer setOverFlag(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager.setOverFlag(MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getBoolean(criterion, "OverFlag"));
    }

    /**
     * 审核生产指示书数据。
     * <p>
     * @param criterion 要审核生产指示书对象。
     * @return 影响行数.
     * @throws Exception
     */
    @RequestMapping(value = "/check.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> check(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager.doCheck(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "WorkFlowId"),
                MapUtils.getShort(criterion, "NodeOrder"),
                MapUtils.getLong(criterion, "CheckedBy"),
                MapUtils.getShort(criterion, "IsCheckCurrentNode")
        );
    }

    /**
     * 反审生产指示书数据。
     * <p>
     * @param criterion 要审核生产指示书对象。
     * @return 影响行数.
     * @throws Exception
     */
    @RequestMapping(value = "/uncheck.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> unCheck(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager.doUnCheck(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "WorkFlowId"),
                MapUtils.getShort(criterion, "NodeOrder"),
                MapUtils.getLong(criterion, "CheckedBy")
        );
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="款号处理部分">
    /**
     * 取得对应生产指示书的款号
     * <p>
     * @param headerId 生产指示书ID
     * @return 款号
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/styleno/fetchByHeaderId.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<ProductionInstructionLinesSuitStyleNoEntity> fetchStyleNoByHeaderId(@RequestBody final Long headerId) throws Exception {
        List<ProductionInstructionLinesSuitStyleNoEntity> _result = _manager_lines_suite_styleno.fetchByHeaderId(headerId);
        return _result == null ? new ArrayList() : _result;
    }

    /**
     * 新增、更新款号
     *
     * @param criterion 要增加或者编辑的数据
     * @return 处理后的明细。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/styleno/save.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> saveStyleNo(@RequestBody final Map<String, ? extends List<ProductionInstructionLinesSuitStyleNoEntity>> criterion) throws Exception {
        return _manager_lines_suite_styleno.saveLines(criterion);
    }

    /**
     * 删除款号
     *
     * @param criterion 要删除的数据
     * @return 处理后的明细。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/styleno/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> deleteStyleNo(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_suite_styleno.delete(criterion);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="明细-数据处理部分">
    /**
     * 根据主表标识取得生产指示书明细数据。
     *
     * @param headerId 产品标识
     * @return 生产指示书明细数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/fetchLinesByHeaderKey.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchLinesByHeaderId(@RequestBody final Long headerId) throws Exception {
        Map<String, Object> _result = _manager_lines.fetchLinesByHeaderId(headerId);
        _result = _result == null ? new HashMap() : _result;

        return _result;
    }

    /**
     * 增加生产指示书计划明细数据。
     *
     * @param criterion 要增加的明细数据
     * @return 新增后的明细数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/insert.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> batchInsert(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines.batchInsert(criterion);
    }

    /**
     * 根据已有明细增加新颜色行数据。
     *
     * @param criterion 要增加的明细数据
     * @return 新增后的明细数据。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/insertLinesByNewColour.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> insertLinesByNewColour(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines.insertLinesByNewColour(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "ColourId"));
    }

    /**
     * 更新生产指示书计划明细数据。
     *
     * @param itemList 要保存的数据
     * @return 影响的行数。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/update.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateLines(@RequestBody final List<ProductionInstructionLinesEntity> itemList) throws Exception {
        if (itemList.isEmpty()) {
            return new HashMap();
        } else {
            return _manager_lines.batchUpdate(itemList);
        }
    }

    /**
     * 更新生产指示书计划明细(套装尺码)数据。
     *
     * @param criterion 要更新的数据
     * @return 更新后的尺码。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/size/update.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateLinesSuitSize(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_suite_size.saveSuitSize(criterion);
    }

    /**
     * 根据生产指示书明细标识取得款的尺码数据。
     *
     * @param criterion 生产指示书明细标识
     * @return 更新后的尺码。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/size/fetchSuitSizeByParentLinesId.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<ProductionInstructionLinesSuitSizeEntity> fetchSuitSizeByLinesId(
            @RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_suite_size.fetchSuitSizeByParentLinesId(
                MapUtils.getString(criterion, "LinesId"));
    }

    /**
     * 更新生产指示书计划明细(颜色)数据。
     *
     * @param itemList 要保存的数据
     * @return 影响的行数。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/colour/update.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateLinesColour(@RequestBody final List<ProductionInstructionLinesEntity> itemList) throws Exception {
        if (itemList.isEmpty()) {
            return new HashMap();
        } else {
            return _manager_lines.updateLinesColour(itemList);
        }
    }

    /**
     * 更新生产指示书计划明细(唛头号)数据。
     *
     * @param itemList 要保存的数据
     * @return 影响的行数。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/shippingmark/update.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateLinesShippingMarkNo(@RequestBody final List<ProductionInstructionLinesEntity> itemList) throws Exception {
        return _manager_lines.updateLinesShippingMarkNo(itemList);
    }

    /**
     * 删除生产指示书计划明细数据。
     *
     * @param criterion 要删除的数据
     * @return 删除后的明细。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> deleteLines(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines.delete(criterion);
    }

    /**
     * 批量删除生产指示书计划明细数据。
     *
     * @param itemList 要删除的数据
     * @return 删除后的明细。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/batch_delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> batchDeleteLines(@RequestBody final List<ProductionInstructionLinesEntity> itemList) throws Exception {
        return _manager_lines.batchDelete(itemList);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="明细-交付日期处理部分">
    /**
     * 新增、更新交付日期。
     *
     * @param criterion 要增加或者编辑的数据
     * @return 处理后的明细。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/schedule/save.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> saveSchedule(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_schdule.saveSchedule(criterion);
    }

    /**
     * 删除生产指示书计划明细（交付日期）数据。
     *
     * @param criterion 要删除的数据
     * @return 处理后的明细。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/schedule/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> deleteSchedule(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_schdule.delete(criterion);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="生产指示书图片处理部分">
    /**
     * 保存生产指示书图片数据。
     * <p>
     * @param instance 要保存的生产指示书图片对象。
     * @return 新增记录主键.
     * @throws Exception
     */
    @RequestMapping(value = "/picture/save.html",
            method = RequestMethod.POST,
            produces = {"application/json"})
    public @ResponseBody
    Map<String, Object> savePicture(@RequestBody final ProductionInstructionLinesPictureEntity instance) throws Exception {
        Map<String, Object> _result = new HashMap();
        _result.put("PictureId", _manager_lines_pic.insert(instance));

        return _result;
    }

    /**
     * 删除生产指示书图片数据。
     *
     * @param instance 生产指示书图片对象
     * @return 影响的行数。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/picture/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Integer deletePicture(@RequestBody final ProductionInstructionLinesPictureEntity instance) throws Exception {
        return _manager_lines_pic.delete(instance);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="颜色及尺码处理部分">
    /**
     * 根据给定的生产指示书标识，取得明细中分配的成品颜色数据
     * <p>
     * @param headerId 生产指示书标识
     * @return 成品颜色数据
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/fetchProductColourByMoHeaderKey.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<Map<String, Object>> fetchProductColourByMoHeaderKey(@RequestBody final Long headerId) throws Exception {
        List<Map<String, Object>> _result = _manager_lines.fetchProductColourFromMoByHeaderId(headerId);
        return _result == null ? new ArrayList() : _result;
    }

    /**
     * 根据给定的产品标识取得对应生产指示书中分配的成品颜色数据
     * <p>
     * @param criterion 产品标识
     * @return 成品颜色数据
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/fetchProductColourByProductId.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<Map<String, Object>> fetchProductColourByProductId(
            @RequestBody final Map<String, Object> criterion) throws Exception {
        List<Map<String, Object>> _result = _manager_lines.fetchProductColourFromMoByProductId(MapUtils.getLong(criterion, "ProductId"));
        return _result == null ? new ArrayList() : _result;
    }

    /**
     * 得到生产指示书计划明细的颜色顺序。
     *
     * @param headerId 生产指示书标识
     * @return 该生产指示书的颜色及顺序。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/fetchColourOrder.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<ProductionInstructionLinesColourOrderEntity> fetchLinesColourOrder(
            @RequestBody final Long headerId) throws Exception {
        List<ProductionInstructionLinesColourOrderEntity> _result = _manager_lines.fetchLinesColourOrderByHeaderId(headerId);
        return _result == null ? new ArrayList() : _result;
    }

    /**
     * 设置生产指示书计划明细的颜色顺序。
     *
     * @param itemList 要更新的颜色顺序
     * @return 更新后的生产指示书明细
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/updateColourOrder.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateLinesColourOrder(@RequestBody final List<Map<String, Object>> itemList) throws Exception {
        return _manager_lines.updateLinesColourOrder(itemList);
    }

    /**
     * 根据给定的产品标识取得对应生产指示书中的成品尺码数据
     * <p>
     * @param criterion 产品标识
     * @return 成品颜色数据
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/fetchProductSizeByProductId.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<Map<String, Object>> fetchProductSizeByProductId(@RequestBody final Map<String, Object> criterion) throws Exception {
        List<Map<String, Object>> _result = _manager_lines.fetchProductSizeFromMoByProductId(MapUtils.getLong(criterion, "ProductId"));
        return _result == null ? new ArrayList() : _result;
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="编辑发货目的地">
    /**
     * 取得发货目的地。
     *
     * @param headerId 要增加或者编辑的数据
     * @return 处理后的明细。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/destination/fetch.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<ProductionInstructionLinesDestinationEntity> fetchDestinationByHeaderId(@RequestBody final Long headerId) throws Exception {
        return _manager_lines_destination.fetchByHeaderId(headerId);
    }

    /**
     * 新增、更新发货目的地。
     *
     * @param criterion 要增加或者编辑的数据
     * @return 处理后的明细。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/destination/save.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> saveDestination(
            @RequestBody final Map<String, ? extends List<ProductionInstructionLinesDestinationEntity>> criterion) throws Exception {
        return _manager_lines_destination.save(criterion);
    }

    /**
     * 删除发货目的地。
     *
     * @param criterion 要删除的数据
     * @return 处理后的明细。
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/destination/delete.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> deleteDestination(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager_lines_destination.delete(criterion);
    }

    /**
     * 设置发货目的地顺序。
     *
     * @param itemList 要更新的发货目的地顺序
     * @return 更新后的生产指示书明细
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/lines/destination/order/update.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> updateDestinationOrder(@RequestBody final List<ProductionInstructionLinesDestinationEntity> itemList) throws Exception {
        return _manager_lines_destination.updateDestinationOrder(itemList);
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="数据补全处理部分">
    /**
     * 根据输入的款号从生产指示书中补齐款号
     *
     * @param criterion 部分款号
     * @return 补全的款号列表
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/fetchStyleNoForAutoComplate.html",
            method = RequestMethod.POST)
    public @ResponseBody
    List<String> fetchStyleNoForAutoComplate(@RequestBody final Map<String, Object> criterion) throws Exception {
        if (criterion.get("keyword") != null) {
            return _manager.fetchStyleNoForAutoComplate(MapUtils.getString(criterion, "keyword"));
        } else {
            return new ArrayList();
        }
    }
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="打印处理部分">
    /**
     * 取得打印数据
     *
     * @param criterion 条件
     * @return 打印数据
     * @throws java.lang.Exception
     */
    @RequestMapping(value = "/print/fetch.html",
            method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> fetchPrintData(@RequestBody final Map<String, Object> criterion) throws Exception {
        return _manager.fetchPrintData(
                MapUtils.getLong(criterion, "HeaderId"),
                MapUtils.getLong(criterion, "CurrentUserId"),
                MapUtils.getLong(criterion, "WorkFlowId"));
    }

    /**
     * 导出发货明细excel文件
     *
     * @param response 客户端响应
     * @param request 客户端请求
     * @throws IOException
     */
    @RequestMapping(value = "/export_to_excel.html", method = RequestMethod.POST)
    public void exportToExcel(HttpServletResponse response, HttpServletRequest request) throws Exception {
        long _headerId = Long.parseLong(request.getParameter("_ExportHeaderId").trim());

        String filename = "生产指示书.xls";
        String tempFilePath = request.getServletContext().getRealPath("/") + "/WEB-INF/templates/01_trade/";

        Map<String, Object> data = _manager.fetchPrintData(_headerId, 0L, null);
        double colours = ((List) data.get("ColourList")).size();
        data.put("Rows", java.lang.Math.ceil(colours / 2));

        try (OutputStream out = response.getOutputStream()) {
            response.reset();                                                   // 清空输出流
            response.setHeader("Content-disposition", "attachment; filename="
                    + new String(filename.getBytes("GB2312"), "ISO8859-1"));    // 设定输出文件头
            response.setContentType("application/msexcel");                     // 定义输出类型

            /**
             * **********创建工作簿************
             */
            parse("01_trade/生产指示书.ftl", data, out);
            out.flush();
        }
    }

    private void parse(String templateName, Map<String, Object> data, OutputStream out) throws IOException, TemplateException {
        try (OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8")) {
            Configuration cfg = freemarkerConfig.getConfiguration();
            //cfg.setDirectoryForTemplateLoading(new File(templateFileDirectory));
            // 加载模板
            Template template = cfg.getTemplate(templateName, "utf-8");
            // 填充数据至Excel
            template.process(data, writer);
            writer.flush();
        }
    }
    // </editor-fold>
}
